<?php
class CategoryModel extends Model
{
    const MAX_DEPTH = 2;

    public function getAllCategories()
    {
        return $this->_db->fetchAllKeyed('
            SELECT *
            FROM product_category
            ORDER BY display_order, name
        ', 'product_category_id');
    }

    public function getCategoriesForMenu()
    {
        $categories = $this->getAllCategories();

        return $this->_getCategoryHierarchy(0, $categories, 1);
    }

    protected function _getCategoryHierarchy($parentId, array &$categories, $depth)
    {
        $children = array();

        if ($depth > self::MAX_DEPTH || empty($categories))
        {
            return $children;
        }

        foreach ($categories as $categoryId => $category)
        {
            if ($category['parent_id'] == $parentId)
            {
                $children[$categoryId] = $category;

                $children[$categoryId]['children'] = $this->_getCategoryHierarchy(
                    $categoryId, $categories, $depth + 1
                );

                unset($categories[$categoryId]);
            }
        }

        return $children;
    }
}
